package cn.takujo.takujoframework.common.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassUtil {

	/**
	 * 通过包获取包内所有类
	 * 
	 * @param pkg
	 *            包对象
	 * @return class集合
	 */
	public static List<Class<?>> getClassesByPackage(Package pkg) {
		return findClasses(pkg.getName());
	}

	/**
	 * 通过包名获取包内所有类
	 * 
	 * @param packageName
	 *            包名
	 * @return class集合
	 */
	public static List<Class<?>> getClassesByPackageName(String packageName) {
		Package pac = Package.getPackage(packageName);
		if (pac != null) {
			return findClasses(packageName);
		} else {
			return new ArrayList<>();
		}
	}

	/**
	 * 通过接口名取得某个接口下所有实现这个接口的类或继承接口
	 * 
	 * @param c
	 *            接口的class
	 * @return class集合
	 */
	public static List<Class<?>> getInterfaceImplClasses(Class<?> c) {
		List<Class<?>> returnClassList = null;
		if (c.isInterface()) {
			String packageName = c.getPackage().getName();
			List<Class<?>> allClass = findClasses(packageName);
			if (!allClass.isEmpty()) {
				returnClassList = new ArrayList<Class<?>>();
				for (Class<?> cls : allClass) {
					// 判断是否为实现类或接口继承
					if (c.isAssignableFrom(cls)) {
						// 接口本身不加入进去
						if (!c.equals(cls)) {
							returnClassList.add(cls);
						}
					}
				}
			}
		}
		return returnClassList;
	}

	/**
	 * 从包package中获取所有的Class
	 * 
	 * @param pack
	 *            包名
	 * @return class集合
	 */
	private static List<Class<?>> findClasses(String packageName) {
		List<Class<?>> classes = new ArrayList<Class<?>>();
		String packageDirName = packageName.replace('.', '/');
		Enumeration<URL> dirs;
		try {
			dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
			while (dirs.hasMoreElements()) {
				URL url = dirs.nextElement();
				String protocol = url.getProtocol();
				if ("file".equals(protocol)) {
					String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
					findClassesByFile(packageName, filePath, classes);
				} else if ("jar".equals(protocol)) {
					findClassesByJar(url, packageDirName, packageName, classes);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return classes;
	}

	/**
	 * 以文件的形式来获取包下的所有Class
	 * 
	 * @param packageName
	 * @param packagePath
	 * @param recursive
	 * @param classes
	 */
	private static void findClassesByFile(String packageName, String packagePath, List<Class<?>> classes) {
		File dir = new File(packagePath);
		if (!dir.exists() || !dir.isDirectory()) {
			return;
		}
		File[] dirfiles = dir.listFiles(new FileFilter() {
			public boolean accept(File file) {
				return (file.isDirectory()) || (file.getName().endsWith(".class"));
			}
		});
		for (File file : dirfiles) {
			if (file.isDirectory()) {
				findClassesByFile(packageName + "." + file.getName(), file.getAbsolutePath(), classes);
			} else {
				String className = file.getName().substring(0, file.getName().length() - 6);
				try {
					classes.add(Class.forName(packageName + '.' + className));
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 以jar的形式来获取包下的所有Class
	 * 
	 * @param url
	 * @param packageDirName
	 * @param packageName
	 * @param classes
	 */
	private static void findClassesByJar(URL url, String packageDirName, String packageName, List<Class<?>> classes) {
		JarFile jar;
		try {
			jar = ((JarURLConnection) url.openConnection()).getJarFile();
			Enumeration<JarEntry> entries = jar.entries();
			while (entries.hasMoreElements()) {
				JarEntry entry = entries.nextElement();
				String name = entry.getName();
				if (name.charAt(0) == '/') {
					name = name.substring(1);
				}
				if (name.startsWith(packageDirName)) {
					int idx = name.lastIndexOf('/');
					if (idx != -1) {
						packageName = name.substring(0, idx).replace('/', '.');
					}
					if (idx == -1) {
						if (name.endsWith(".class") && !entry.isDirectory()) {
							String className = name.substring(packageName.length() + 1, name.length() - 6);
							try {
								classes.add(Class.forName(packageName + '.' + className));
							} catch (ClassNotFoundException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
